import React from 'react';
import { formatToBeijingTime } from '../utils/timeUtils';

// 通用数据表格组件
const DataTable = ({ 
  data = [], 
  title, 
  loading, 
  error, 
  onRefresh,
  columnConfig = [] // 列配置数组，定义如何显示数据
}) => {
  // 如果没有提供列配置，自动生成列（基于第一行数据的键）
  const generateColumns = (data) => {
    if (!data || data.length === 0) return [];
    
    const firstRow = data[0];
    return Object.keys(firstRow).map(key => ({
      key,
      title: key,
      render: (value) => String(value)
    }));
  };

  const columns = columnConfig.length > 0 ? columnConfig : generateColumns(data);

  return (
    <div style={{ 
      border: '1px solid #ddd', 
      borderRadius: '5px', 
      padding: '15px',
      backgroundColor: '#f9f9f9'
    }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: '15px' 
      }}>
        <h3>{title}</h3>
        {onRefresh && (
          <button
            onClick={onRefresh}
            disabled={loading}
            style={{
              padding: '6px 12px',
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: loading ? 'not-allowed' : 'pointer',
              fontSize: '12px'
            }}
          >
            {loading ? '刷新中...' : '刷新'}
          </button>
        )}
      </div>
      
      {error && (
        <div style={{ 
          color: 'red', 
          marginBottom: '15px', 
          padding: '8px', 
          backgroundColor: '#ffe6e6',
          border: '1px solid #ff0000',
          borderRadius: '4px'
        }}>
          <strong>错误:</strong> {error}
        </div>
      )}

      <p>共找到 {data.length} 条记录</p>
      
      {data.length > 0 ? (
        <div style={{ maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}>
          <table style={{ borderCollapse: 'collapse', width: '100%', fontSize: '14px', tableLayout: 'auto' }}>
            <thead>
              <tr>
                {columns.map((col, index) => (
                  <th 
                    key={col.key || index} 
                    style={{ 
                      border: '1px solid #ddd', 
                      padding: '12px', 
                      backgroundColor: '#f2f2f2', 
                      position: 'sticky', 
                      top: 0,
                      minWidth: '100px',
                      textAlign: 'left',
                      zIndex: 10
                    }}
                  >
                    {col.title}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data.map((row, rowIndex) => (
                <tr key={row.id || rowIndex}>
                  {columns.map((col, colIndex) => (
                    <td 
                      key={col.key || colIndex} 
                      style={{ 
                        border: '1px solid #ddd', 
                        padding: '12px',
                        wordBreak: 'break-word',
                        backgroundColor: rowIndex % 2 === 0 ? '#fff' : '#f9f9f9'
                      }}
                    >
                      {col.render ? col.render(row[col.key], row) : (
                        row[col.key] !== undefined && row[col.key] !== null ? 
                        (typeof row[col.key] === 'object' ? JSON.stringify(row[col.key]) : String(row[col.key])) : 
                        ''
                      )}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <p>暂无数据</p>
      )}
    </div>
  );
};

// 专门用于显示货位数据的组件（继承自通用表格组件）
const SlotTable = ({ slots, title, loading, error, onRefresh }) => {
  // 货位列配置
  const slotColumnConfig = [
    { key: 'id', title: 'ID' },
    { key: 'layer', title: '层' },
    { key: 'row', title: '排' },
    { key: 'column', title: '列' },
    { 
      key: 'created_at', 
      title: '创建时间',
      render: (value) => formatToBeijingTime(value)
    },
    { 
      key: 'updated_at', 
      title: '更新时间',
      render: (value) => formatToBeijingTime(value)
    }
  ];

  return (
    <DataTable
      data={slots}
      title={title}
      loading={loading}
      error={error}
      onRefresh={onRefresh}
      columnConfig={slotColumnConfig}
    />
  );
};

export { DataTable, SlotTable };
export default SlotTable;